const FtpClient = require('ftp');
const fs = require('fs');
const client = new FtpClient();
class UploadPlugin {
    constructor(options) {
        this.options = options || {
            sourcePath: `./release/dist.zip`,
            targetPath: `/dist.zip`,
            config: {
                host: '192.168.252.72',
                port: 10021,
                user: 'fuser',
                password: 'tmkj@zgb123',
                keepalive: 10000,
            },
        };
    }

    apply(compiler) {
        compiler.hooks.afterEmit.tapPromise('UploadPlugin', (compilation) => {
            return this.upload(this.options.sourcePath, this.options.targetPath);
        });
    }
    async upload(sourcePath, targetPath) {
        if (!fs.existsSync(sourcePath)) {
            return false;
        }
        await this.connect();
        return new Promise((resolve, reject) => {
            client.put(sourcePath, targetPath, (err) => {
                client.end();
                if (err) {
                    console.log(err);
                    reject(false);
                } else {
                    console.log(`upload file completed. filePath: ${targetPath}`);
                    resolve(true);
                }
            });
        });
    }
    connect() {
        return new Promise((resolve, reject) => {
            client.on('ready', () => {
                console.log('ftp ready');
                resolve();
            });
            client.on('close', () => {
                console.log('ftp close');
            });
            client.on('end', () => {
                console.log('ftp end');
            });
            client.on('error', (err) => {
                console.log('ftp err', err);
                reject(err);
            });
            client.connect(this.options.config);
        });
    }
}

module.exports = UploadPlugin;
